package com.caimiao.miao.page.master.system.lottery;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.caimiao.miao.R;
import com.caimiao.miao.library.usb.logic.UsbCode;
import com.caimiao.miao.library.usb.accessory.Command;

import java.util.List;

public class CommandAdapter extends BaseAdapter {
    private List<Command> mDataList;
    private LayoutInflater mInflater;

    public CommandAdapter(Context context, List<Command> mDataList) {
        this.mDataList = mDataList;
        mInflater = LayoutInflater.from(context);
    }

    public void addCommand(Command command) {
        if (command != null) {
            mDataList.add(0, command);
            notifyDataSetChanged();
        }
    }

    @Override
    public int getCount() {
        if (mDataList != null)
            return mDataList.size();
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return mDataList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final Holder mHolder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.item_command, parent, false);
            mHolder = new Holder(convertView);
            convertView.setTag(mHolder);
        } else {
            mHolder = (Holder) convertView.getTag();
        }
        final Command data = mDataList.get(position);
        String status = data.getStatus() == UsbCode.SCHEDULER_STATUS_TIMEOUT ? "超时：接收超时啦!!!\n" :
                data.getStatus() == UsbCode.SCHEDULER_STATUS_READ ? "接收：" : "发送：";
        StringBuilder sb = new StringBuilder();
        sb.append(data.getDate());
        sb.append(" ");
        sb.append(status);
        int length = data.getCommand() == null ? 0 : data.getCommand().length;
        for (int i = 0; i < length; i++) {
            int t = data.getCommand()[i];
            if (t < 0) t = t + 256;
            if (t < 16) sb.append("0");
            sb.append(Integer.toHexString(t));
            sb.append(" ");
        }
        mHolder.mTvContent.setText(sb.toString());
        mHolder.mTvContent.setTextColor(data.getColor());
        return convertView;
    }

    private class Holder {
        TextView mTvContent;

        public Holder(View convertView) {
            mTvContent = convertView.findViewById(R.id.itemTvContent);
        }
    }
}
